# -*- coding: utf-8 -*-
"""
@Time ： 2024/8/1 15:30
@Auth ： 李天天
"""
import shutil
import time
import requests
import pytest
import json
import os
import subprocess
import zipfile
from datetime import datetime
from Common.global_data import GlobalData
from Common.basepage import BasePage
from Common.handle_yaml import do_yaml
from Common.connect_to_device import *
import read_log

do_basepage = BasePage(device="d_one")
# 钉钉机器人 webhook 地址
# DINGTALK_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=22dd0dacb7476ca49c51a9cf121b2850f2519cbda2df44e6af8f1ffeae76aad3' #测试用
DINGTALK_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=bfb9aa2aabb8c9fd74d4353c65db4b676a3371073a46fe353efb3cbdc78ee372'
title = do_yaml.read("report", "title")
version = do_yaml.read("report", "version")
device = do_yaml.read("report", "device")
executor = do_yaml.read("report", "executor")
allure_path = do_yaml.read("report", "allure_path")


# 运行 pytest 并生成 Allure 报告
def run_pytest():
    do_basepage.close_IQIYI_app()
    pytest.main([
        "-s",
        # "-m test",
        "--alluredir=Outputs/allure_result_files",
        "--clean-alluredir"
    ])



def send_dingtalk_message(summary: dict, title, version, device, executor, test_time, allure_url=None):
    headers = {'Content-Type': 'application/json'}
    message = {
        "msgtype": "markdown",
        "markdown": {
            "title": "测试报告",
            "text": (
                f"### 测试报告\n\n"
                f"**标题:** {title}\n\n"
                f"**测试版本:** {version}\n\n"
                f"**测试设备:** {device}\n\n"
                f"**执行人员:** {executor}\n\n"
                f"**总用例数:** {summary.get('Total')}\n\n"
                f"**未勾选数:** {summary.get('Deselected')}\n\n"
                f"**本次运行用例数:** {summary.get('Total') - summary.get('Skipped') - summary.get('Deselected')}\n\n"
                f"**通过数:** {summary.get('Passed')}\n\n"
                f"**失败数:** {summary.get('Failed')}\n\n"
                f"**错误数:** {summary.get('Errors')}\n\n"
                f"**跳过数:** {summary.get('Skipped')}\n\n"
                f"**用例通过率:** {summary.get('SuccessRate')}\n\n"
                f"**开始测试:** {test_time}\n\n"
                f"**总运行时间:** {summary.get('TotalTime')}\n\n"
                f"[Allure报告详情]({allure_url})\n\n"
                f"[报告管理平台](http://10.10.118.92:8888)"
            )
        }
    }
    requests.post(DINGTALK_WEBHOOK, json=message, headers=headers)


def zipdir(path, ziph):
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file), os.path.relpath(os.path.join(root, file), os.path.join(path, '..')))


def send_report(title, version, device, executor, test_time, results):
    zipf = zipfile.ZipFile('allure_report.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('Outputs/allure_report', zipf)
    zipf.close()

    with open("allure_report.zip", "rb") as f:
        response = requests.post(
            "http://10.10.118.92:8888/upload-report/",
            files={"file": f},
            data={"title": title, "version": version, "device": device, "executor": executor,
                  "test_time": test_time.isoformat(),
                  "results": json.dumps(results)}
        )

    # os.remove("allure_report.zip")
    pass
    return response.json()


if __name__ == "__main__":
    # 运行测试
    current_time = datetime.now()
    title= "5D自动化调试"
    version=app_version
    device= device_type
    executor="徐基业"
    # 格式化时间为指定格式
    formatted_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
    do_basepage.close_IQIYI_app()
    # airConditioner: 空调 SeatMove 座椅移动 SeatVentilation座椅通风 SeatMassage: 座椅按摩 SeatHeating 座椅加热
    # SeatRhythm: 座椅律动 SeatAtomizationVibration: 原子化振动 AtmosphereLights:氛围灯 Fragrance 香薰
    pytest.main([
        "-s",
        # "-m test",
        "--alluredir=Outputs/allure_result_files",
        "--clean-alluredir"
    ])
    os.system(f"allure generate Outputs/allure_result_files -o Outputs/allure_report --clean")
    # 获取报告
    try:
        summary = getattr(GlobalData, "summary")
        report_info = send_report(title=title, version=version, device=device, executor=executor,test_time=current_time,results=summary)
        print(report_info)
        url=report_info["report_url"]
    except:
        url="http://www.baidu.com"
    # 发送钉钉消息
    send_dingtalk_message(summary, title=title, version=version, device=device, executor=executor,test_time=formatted_time, allure_url=report_info["report_url"])
    # 处理结果文件
    read_log.send_dingding()
